﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Extentions;
using Microsoft.AspNetCore.Http;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NStandard;
using TrainingReminderSystem.Dal;
using TrainingReminderSystem.Model;

namespace TrainingReminderSystem.Bll;

/// <summary>
/// 测试用的bll
/// </summary>
public class TestBll : PcLoginedBll
{
    //public AjaxResult<int> TestExecuteSqlCommand()
    //{
    //    AjaxResult<int> r = new AjaxResult<int>();
    //    using (var db = Db)
    //    {
    //        using (var tran = db.Database.BeginTransaction())
    //        {
    //            int count = db.Database.ExExecuteSqlCommand("update Project set ProjectName='测试2' where ProjectID=2");
    //            r.Result = count;
    //            tran.Rollback();
    //        }
    //    }
    //    r.Success = true;
    //    return r;
    //}

    //public AjaxResult<dynamic> TestFilter()
    //{
    //    using (var db = Db)
    //    {
    //        var list = db.TblTest.ToList();
    //    }
    //    using (var db = Db)
    //    {
    //        var list = db.StatisticalSql.ToList();
    //    }
    //    using (var db = Db)
    //    {
    //    }
    //    using (var db = Db)
    //    {
    //    }
    //    using (var db = Db)
    //    {
    //        var list = db.StatisticalSql.ToList();
    //    }
    //    using (var db = Db)
    //    {
    //        var list = db.TblTest.ToList();
    //        return AjaxResult<dynamic>.SuccessResult(list);
    //    }
    //}

    // #region 添加和编辑的时候 验证数据和设置默认值

    // /// <summary> /// 添加和编辑的时候 验证数据和设置默认值 /// </summary> /// <param name="db"></param> /// <param
    // name="model"></param> /// <param name="isAdd">添加还是编辑,可以不管此参数</param> ///
    // <returns>是否通过,true表示验证通过,false代表验证没有通过</returns> public AjaxResult<dynamic>
    // Validate(DbEntities db, TblTest model, bool isAdd) { AjaxResult<dynamic> r = new
    // AjaxResult<dynamic>(); if (model == null) { r.Message = LanguageHelper.NoSubmitData; return
    // r; }

    // if (string.IsNullOrEmpty(model.TblTestName)) { //r.Message =
    // LanguageHelper.GetString<TblTest>(nameof(model.TblTestName)); r.Message =
    // LanguageHelper.RequireString1<TblTest>(nameof(model.TblTestName)); //r.Message =
    // model.ExRequireString1(nameof(model.TblTestName)); return r; }

    // r.Success = true; return r; }

    // #endregion

    // #region 新增方法

    // public AjaxResult<dynamic> TblTestSave(TblTest model) { using (var db = Db) { if (model.ID >
    // 0) { return TblTestUpdate(model, db); }

    // return TblTestAdd(model, db); } }

    // internal AjaxResult<dynamic> TblTestAdd(TblTest model, DbEntities db) { var r = new
    // AjaxResult<dynamic>() { Success = false }; var tempAr = Validate(db, model, true); if
    // (tempAr.Success == false) { r.Message = tempAr.Message; r.Result = tempAr.Result; r.Total =
    // tempAr.Total; return r; } IDbContextTransaction tran = db.Database.CurrentTransaction; bool
    // hasTran = tran != null; if (hasTran == false) tran = db.Database.BeginTransaction(); try { db.TblTest.Add(model);

    // string error = AddLog(db, model, EnumLogType.新建); if (!string.IsNullOrEmpty(error)) { return
    // AjaxResult<dynamic>.ErrorResult(error); } db.SaveChanges(); if (hasTran == false) {
    // tran.Commit(); tran.Dispose(); tran = null; } r.Success = true; r.Message =
    // LanguageHelper.Success; r.Result = model.ID; return r; } finally { if (hasTran == false &&
    // tran != null) { tran.Rollback(); tran.Dispose(); } } }

    // #endregion

    // #region 编辑方法

    // internal AjaxResult<dynamic> TblTestUpdate(TblTest model, DbEntities db) { var r = new
    // AjaxResult<dynamic>() { Success = false }; var tempAr = Validate(db, model, false); if
    // (tempAr.Success == false) { r.Message = tempAr.Message; r.Result = tempAr.Result; r.Total =
    // tempAr.Total; return r; } IDbContextTransaction tran = db.Database.CurrentTransaction; bool
    // hasTran = tran != null; if (hasTran == false) tran = db.Database.BeginTransaction(); try {
    // var beforeModel = db.TblTest.FirstOrDefault(m => m.ID == model.ID); if (beforeModel == null)
    // { r.Message = LanguageHelper.NoData; return r; } beforeModel.ExCopyFrom(model);

    // string error = AddLog(db, model, EnumLogType.编辑); if (!string.IsNullOrEmpty(error)) { return
    // AjaxResult<dynamic>.ErrorResult(error); } var isSuccess = db.SaveChanges() >= 0; if (hasTran
    // == false) { tran.Commit(); tran.Dispose(); tran = null; } r.Success = true; r.Message =
    // LanguageHelper.Success; r.Result = model.ID; return r; } finally { if (hasTran == false &&
    // tran != null) { tran.Rollback(); tran.Dispose(); } } }

    // #endregion

    // #region 得到单对象方法

    // public AjaxResult<dynamic> TblTestGet(int id) { using (var db = Db) { var beforeModel =
    // db.TblTest.FirstOrDefault(m => m.ID == id); if (beforeModel == null) { return
    // AjaxResult<dynamic>.ErrorResult(LanguageHelper.NoData); } return
    // AjaxResult<dynamic>.SuccessResult(beforeModel); } }

    // #endregion

    // #region 分页方法

    // private Expression<Func<Model.TblTest, bool>>
    // InitSearchDelegete(Expression<Func<Model.TblTest, bool>> where, string key, string val) {
    // return null; }

    // /// <summary>
    ///// 分页方法
    ///// </summary>
    ///// <param name="index"></param>
    ///// <param name="size"></param>
    ///// <param name="form"></param>
    ///// <param name="sortField"></param>
    ///// <param name="asc"></param>
    ///// <returns></returns>
    //public AjaxResult<dynamic> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
    //      {
    //          using (var db = Db)
    //          {
    //              Expression<Func<TblTest, bool>> where = InitSearch<TblTest>(form, InitSearchDelegete);//拼接查询条件方法
    //              //where = where.ExAnd(m => m.CreateDate < new DateTime(2020, 11, 18)); //有BUG
    //              //弄成变量就没有BUG
    //              //var dt = new DateTime(2020, 11, 18);
    //              //where = where.ExAnd(m => m.CreateDate < dt);
    //              //where = where.ExAnd(m => m.CreateDate >= DateTime.Now); //无BUG,带的是getDate()
    //              //var dt = DateTime.Now;
    //              //where = where.ExAnd(m => m.CreateDate >= dt);////无BUG,带的是 时间变量的那个
    //              //where = where.ExAnd(m => m.CreateDate < EF.Functions.DateTimeFromParts(2020, 11, 18, 0, 0, 0, 0));//正确

    // #region 拼接查询条件

    // if (form != null) { }

    // #endregion

    // int counts; IQueryable<TblTest> tempList = db.TblTest.AsNoTracking().ExOrderBy(sortField,
    // asc).ExGetListByPage(index, size, out counts, where); var result = new AjaxResult<dynamic>()
    // { Success = true }; result.Total = counts;

    // IQueryable<TblTest> list = db.TblTest.AsNoTracking().Where(m => tempList.Any(n => n.ID ==
    // m.ID)).ExOrderBy(sortField, asc); result.Result = list.Select(m => new { m.ID, m.IsDel,
    // m.Remark, m.TblTestName, m.CreateDate, m.CreateEmployeeID }).ToList(); return result; } }

    // #endregion

    // #region 测试表达式

    // public void TestExpress() { ParameterExpression i = Expression.Parameter(typeof(DateTime),
    // "i"); BlockExpression block = Expression.Block( new[] { i }, //赋初值 i=5 Expression.Assign(i,
    // Expression.Constant(DateTime.Now, typeof(DateTime))) ////i+=5 10 //Expression.AddAssign(i,
    // Expression.Constant(5, typeof(int))), ////i-=5 5 //Expression.SubtractAssign(i,
    // Expression.Constant(5, typeof(int))), ////i*=5 25 //Expression.MultiplyAssign(i,
    // Expression.Constant(5, typeof(int))), ////i/=5 5 //Expression.DivideAssign(i,
    // Expression.Constant(5, typeof(int))) );
    // Console.WriteLine(Expression.Lambda<Func<DateTime>>(block).Compile()()); //var resultXXXX =
    // Expression.Lambda(block).Compile(); //Console.WriteLine(resultXXXX);

    // var parameterExp = Expression.Parameter(typeof(TblTest), "m"); //m对象 var propertyExp =
    // Expression.Property(parameterExp, "CreateDate"); DateTime val = DateTime.Now;
    // ParameterExpression varExp = Expression.Variable(typeof(DateTime));

    // ConstantExpression constExp = Expression.Constant((DateTime)val, typeof(DateTime)); //var
    // hoistedConstant = Expression.Property(constExp, "Value"); var hoistedConstan2t =
    // Expression.Property(Expression.Constant(new { Value = val }), "Value"); //NewExpression newA
    // = Expression.New(typeof(DateTime)); //MemberInitExpression test3 =
    // Expression.MemberInit(newA, // new List<MemberBinding>() { } //); var test =
    // Expression.Assign(varExp, constExp); BlockExpression block3 = Expression.Block( new[] {
    // varExp }, Expression.Assign(varExp, constExp) ); var ccccccccc =
    // Expression.Lambda<Func<DateTime>>(block3).Compile()(); Console.WriteLine(ccccccccc);
    // //Expression.Lambda(test).Compile(); var methodCallExpression =
    // Expression.LessThanOrEqual(propertyExp, hoistedConstan2t); //n.LinkName.Contains('张山')
    // Console.WriteLine(methodCallExpression.ToString()); Expression<Func<TblTest, bool>> where =
    // Expression.Lambda<Func<TblTest, bool>>(methodCallExpression, parameterExp);

    // var hoistedConstan2t2 = Expression.Property(Expression.Constant(new { Value = val.AddDays(-5)
    // }), "Value"); var methodCallExpression2 = Expression.GreaterThanOrEqual(propertyExp,
    // hoistedConstan2t2); //n.LinkName.Contains('张山')

    // Expression<Func<TblTest, bool>> where2 = Expression.Lambda<Func<TblTest,
    // bool>>(methodCallExpression2, parameterExp); where = where.ExAnd(where2); using (var db = Db)
    // { int count = db.TblTest.Count(where); Console.WriteLine(count); } }

    // #endregion

    //#region 测试Timestamp

    ///// <summary>
    ///// 测试Timestamp
    ///// </summary>
    //public void TestTimestamp()
    //{
    //    //都用不同的db对象
    //    //新增一条 TblTest
    //    //var addModel = new TblTest()
    //    //{
    //    //    CreateDate = DateTime.Now,
    //    //    ID = 0,
    //    //    TblTestName = "test"
    //    //};
    //    //using (var db = Db)
    //    //{
    //    //    db.TblTest.Add(addModel);
    //    //    db.SaveChanges();
    //    //    Console.WriteLine("添加成功:" + addModel.ID);
    //    //}
    //    //重新查询并COPY一个对象出来 弄两个修改此数据,会有一个是报错的
    //    TblTest addModel = null;
    //    using (var db = Db)
    //    {
    //        addModel = db.TblTest.FirstOrDefault(m => m.ID == 35);
    //    }
    //    var submitModel = new TblTest();
    //    submitModel.ExCopyFrom(addModel);
    //    submitModel.ID = addModel.ID;
    //    Thread thread1 = new Thread(() =>
    //    {
    //        using (var db = Db)
    //        {
    //            try
    //            {
    //                submitModel.TblTestName = "test2";
    //                var beforeModel = db.TblTest.FirstOrDefault(m => m.ID == addModel.ID);
    //                beforeModel.TblTestName = submitModel.TblTestName;
    //                //beforeModel.RowVersion = submitModel.RowVersion;
    //                int count = db.SaveChanges();
    //                Console.WriteLine("1影响行数:" + count);
    //            }
    //            catch (Exception e)
    //            {
    //                Console.WriteLine(e);
    //            }
    //        }

    // }); Thread thread2 = new Thread(() => { using (var db = Db) { //Thread.Sleep(1000); try {
    // submitModel.TblTestName = "test3"; var beforeModel2 = db.TblTest.FirstOrDefault(m => m.ID ==
    // addModel.ID); beforeModel2.TblTestName = submitModel.TblTestName; //beforeModel2.RowVersion =
    // submitModel.RowVersion; int count = db.SaveChanges(); Console.WriteLine("2影响行数:" + count); }
    // catch (Exception e) { Console.WriteLine(e); } } }); thread1.Start(); thread2.Start();

    //    //using (var db = Db)
    //    //{
    //    //    var removeObj = db.TblTest.FirstOrDefault(m => m.ID == addModel.ID);
    //    //    db.TblTest.Remove(removeObj);
    //    //    db.SaveChanges();
    //    //    Console.WriteLine("删除成功:" + addModel.ID);
    //    //}
    //}

    ////界面上,搞一个GetModel方法,然后再给Add方法提交

    //#endregion

    #region 测试多语言

    public void TestLanguage()
    {
        var model = new SysStatisticalSql();
        //属性多语言名称1
        //var r = model.ExLanguageString(nameof(model.StatisticalSqlName));
        //Console.WriteLine(r);
        //属性多语言名称2
        var r = LanguageHelper.GetStringKey<SysStatisticalSql>(nameof(model.StatisticalSqlName));
        Console.WriteLine(r);

        //请输入XXX1
        //r = model.ExRequireString1(nameof(model.StatisticalSqlName));
        //Console.WriteLine(r);
        //请输入XXX2
        r = LanguageHelper.RequireString1<SysStatisticalSql>(nameof(model.StatisticalSqlName));
        Console.WriteLine(r);
        //r = LanguageHelper.GetStringKey(nameof(model.StatisticalSqlName));
        //Console.WriteLine(r);
        //自定义的
        r = LanguageHelper.GetString<SysStatisticalSql>("SqlContent", "参数哈");
        Console.WriteLine(r);

        Console.WriteLine("---------------------------------以下是新方法---------------------------------");
        ModelName = nameof(SysStatisticalSql);
        r = string.Format(lan[nameof(SysStatisticalSql.SqlContent)], "参数传递111111");
        Console.WriteLine(r);
        r = comLan["Custom.SysEmployee.pwdEqual"];
        Console.WriteLine(r);
        r = string.Format(LanguageHelper.Require1, keyLan[nameof(SysStatisticalSql.SqlContent)]);
        Console.WriteLine(r);

        "aa".ExToJson();
    }

    #endregion 测试多语言

    #region 测试配置文件

    public void TestSysSetting()
    {
        var bll = new SysSettingBll();
        //var model = SysSettingBll.GetModel(EnumSettingCode.PC端登录失效时间, 1);
        //Console.WriteLine(model.ExToJson());
        var list = bll.GetListByType(EnumSettingType.系统参数);
        Console.WriteLine(list.ExToJson());
    }

    #endregion 测试配置文件

    #region 测试发送邮件

    public void TestSendEmail()
    {
        MailHelper.SendErrorLog();
    }

    #endregion 测试发送邮件

    #region 测试读取复杂配置文件

    public void TestAppSettingsJson()
    {
        var a = ConfigurationHelper.MailMessage;
        Console.WriteLine(a.ExToJson());
    }

    #endregion 测试读取复杂配置文件

    //#region  测试修改明细数据

    //public void TestChangeDetail()
    //{
    //    using (var db = Db)
    //    {
    //        var beforeList = db.TblTest.ToList();
    //        var submitList = JsonHelper.DeserializeObject<List<TblTest>>(beforeList.ExToJson());
    //        //修改一条,删除一条,新增一条
    //        submitList.FirstOrDefault(m => m.ID == 35).TblTestName = "修改的那一条数据111";
    //        submitList.Remove(submitList.FirstOrDefault(m => m.ID == 42));
    //        submitList.Add(new TblTest()
    //        {
    //            CreateDate = DateTime.Now,
    //            TblTestName = "新增的那一条数据111",
    //            CreateEmployeeID = null,
    //            ID = 0,
    //            IsDel = false,
    //            Remark = ""
    //        });
    //        BaseBll.ChangeDetail(db, beforeList, submitList);
    //        db.SaveChanges();
    //    }
    //}

    //#endregion

    #region 测试拼音

    public void TestPinYin()
    {
        Console.WriteLine("第一次加载特慢 要1秒多");
        var sw = new Stopwatch();
        sw.Start();
        var r = ToolHelper.GetPy("测试拼音");
        sw.Stop();
        Console.WriteLine($"结果:{r},耗时:{sw.ElapsedMilliseconds}毫秒");
        sw.Reset();
        sw.Start();
        var r2 = ToolHelper.GetPy("眉山蓦然软件工作室");
        sw.Stop();
        Console.WriteLine($"结果:{r2},耗时:{sw.ElapsedMilliseconds}毫秒");
        sw.Reset();
        sw.Start();
        var r3 = ToolHelper.GetPy("眉山市东坡区蓦然软件工作室");
        sw.Stop();
        Console.WriteLine($"结果:{r3},耗时:{sw.ElapsedMilliseconds}毫秒");
    }

    #endregion 测试拼音

    #region 测试数据库

    /// <summary>
    /// 测试数据库
    /// </summary>
    public void CheckDb()
    {
        var bll = new SysRolePostBll();
        var r = bll.CheckDb();
        if (r.Success)
        {
            Console.WriteLine("成功");
            Console.WriteLine(r.Message);
        }
        else
        {
            Console.WriteLine("失败");
            Console.WriteLine(r.Message);
        }
    }

    #endregion 测试数据库

    #region 测试函数

    public dynamic TestExecuteScalar(int businessID, int goodsID)
    {
        dynamic res = 0;
        using (var db = Db)
        {
            // db.fn_GetBusinessGoodsMaxSettlementPrice(665,1);
            using (var tran = db.Database.BeginTransaction())
            {
                var count = db.Database.ExSqlQuery(
                    $"SELECT  dbo.fn_GetBusinessGoodsMaxSettlementPrice({businessID},{goodsID})");
                res = count.Rows[0].ItemArray[0];
            }
        }

        return res;
    }

    //public void TestDbFun()
    //{
    //    var bll = new GoodsBll();
    //    var list = bll.GetList("四川省", "成都市", string.Empty);
    //    Console.WriteLine(list.ExToJson());
    //}

    #endregion 测试函数

    #region 测试缓存

    /// <summary>
    /// 缓存的对象,更改对象的属性,缓存里的也跟着改动了,是引用类型的 而Session里存入的,则不是引用类型,因为存入的是字符串,而非对象
    /// </summary>
    public static void TestCache()
    {
        var key = "testKey";
        var obj = new SysEmployee
        {
            SysEmployeeID = 1,
            SysEmployeeName = "aaa"
        };
        CacheHelper.SetAbsoluteCache(key, obj);
        var obj2 = CacheHelper.GetCache(key) as SysEmployee;
        if (obj2 != null) obj2.SysEmployeeID = 2;
        var obj3 = CacheHelper.GetCache(key) as SysEmployee;
        Console.WriteLine(obj3.ExToJson());
        Console.ReadLine();
    }

    #endregion 测试缓存

    #region 测试URL拼接

    public void TestRedirectUrl()
    {
        var code = "123456";
        var redirectUrl = "http://cscz3.ybx365.com/?n=20210616#/dashboard/MyCard";
        if (!string.IsNullOrEmpty(redirectUrl))
        {
            var poundSignIndex = redirectUrl.IndexOf('#');
            var questionMarkIndex = redirectUrl.IndexOf('?');
            string newRedirectUrl;
            if (poundSignIndex == -1) //不存在#的情况
            {
                newRedirectUrl = redirectUrl + (questionMarkIndex == -1 ? "?" : "&") +
                                 "code=" + HttpUtility.UrlEncode(code);
            }
            else //存在#
            {
                if (questionMarkIndex == -1) //存在#不存在?
                {
                    var insert = $"?code={HttpUtility.UrlEncode(code)}";
                    newRedirectUrl = redirectUrl.Substring(0, poundSignIndex) + insert +
                                     redirectUrl.Substring(poundSignIndex);
                }
                else //存在#也存在?
                {
                    var insert = $"&code={HttpUtility.UrlEncode(code)}";
                    if (poundSignIndex < questionMarkIndex) //#在?之前
                        newRedirectUrl = redirectUrl + insert;
                    else //#在?之后
                        newRedirectUrl = redirectUrl.Substring(0, poundSignIndex) + insert +
                                         redirectUrl.Substring(poundSignIndex);
                }
            }

            Console.WriteLine(newRedirectUrl);
            Console.ReadLine();
        }

        Console.WriteLine("code:" + code);
        Console.ReadLine();
    }

    #endregion 测试URL拼接

    #region 测试缓存循环

    public static void TestCacheForeach()
    {
        CacheHelper.SetRelativeCache("aa", "111");
        CacheHelper.SetRelativeCache("bb", "222");
        var list = CacheHelper.GetList("a");
        Console.WriteLine(list.Count);
    }

    #endregion 测试缓存循环

    #region EFCore Contains就是like查询的拼接,不需要使用EF.Functions.Like

    //public static async Task FunctionsLike()
    //{
    //    var bll = new SysEmployeeBll();
    //    //断点查看默认事务级别 ReadCommitted    4096     在正在读取数据时保持共享锁，以避免脏读，但是在事务结束之前可以更改数据，从而导致不可重复的读取或幻像数据。
    //    //var beforeModel = bll.GetModel(1).Result;
    //    //beforeModel.SysEmployeeName = "admin";
    //    //AjaxResult<dynamic> tempAr = bll.Update(beforeModel);
    //    //Console.WriteLine(tempAr.ExToJson());
    //    var projectBll = new ProjectBll();
    //    ProjectExPost modifyModelTemp = new ProjectExPost()
    //    {
    //        ProjectID = 1,
    //        EnumProjectType = EnumProjectType.本地开发,
    //        IpInfo = "127.0.0.1",
    //        UrlDomain = "http://localhost:8801/",
    //        Remark = "123"
    //    };
    //    Project modifyModel = new Project();
    //    modifyModel.ExCopyFrom(modifyModelTemp);
    //    var arTemp = await projectBll.Modify(modifyModel);
    //    Console.WriteLine(arTemp.ExToJson());
    //    Console.WriteLine("后续的是测试ModifyBase2方法");
    //    return;
    //    using var db = Db;
    //    //db.TblTest.ToList(); 测试一下查询
    //    const string sysOperatorLoginPwd = "测试%";
    //    try
    //    {
    //        string name = "test_" + DateTime.Now.ExToLong();
    //        SysEmployee model = new SysEmployee()
    //        {
    //            SysEmployeeID = -1,
    //            SysEmployeeName = name
    //        };
    //        int count = ModifyBase2(model, db, "SysEmployeeName");
    //        model.SysEmployeeName = "2" + name;
    //        int count1 = await db.SaveChangesAsync();
    //        Console.WriteLine($"name:{name} count:{count} count1:{count1}");
    //    }
    //    catch (Exception ex)
    //    {
    //        Console.WriteLine($"{ex.GetType().FullName}\r\n{ex.ExFullString()}");
    //    }

    // Console.WriteLine("之后测试包含的拼接语句,结论是 字符串的用常量对象,就只有like拼接"); return; Dictionary<string,
    // StringValues> dic = new Dictionary<string, StringValues>() { { "SysOperator.LoginPwd",
    // sysOperatorLoginPwd } }; IFormCollection form = new FormCollection(dic); //string tempValue =
    // form["SysOperator.LoginPwd"].ExTrim();//变量形式不行,生成的sql多余了 //DECLARE @__tempValue_0
    // nvarchar(4000) = N'测试%'; //SELECT[s].[SysEmployeeID], [s].[CanSeePhone],
    // [s].[EnumQuitStatus], [s].[HeaderUrl], [s].[IsDel], [s].[IsDemo], [s].[PY], [s].[Remark],
    // [s].[SysEmployeeName], [s].[SysEmployeePhone], [s].[SysOperatorID], [s].[UpdateDate],
    // [s].[UpdateEmployeeID], [s].[UserCode] //FROM[SysEmployee] AS[s] //LEFT JOIN[SysOperator]
    // AS[s0] ON[s].[SysOperatorID] = [s0].[SysOperatorID] //WHERE([s].[IsDel] = CAST(0 AS bit))
    // AND((@__tempValue_0 LIKE N'') OR(CHARINDEX(@__tempValue_0, [s0].[LoginPwd]) > 0))
    // Expression<Func<SysEmployee, bool>> where = m =>
    // m.SysOperator.LoginPwd.Contains(sysOperatorLoginPwd); var temp = db.SysEmployee.Where(where);
    // var list = await temp.ToListAsync(); Console.WriteLine(list.Count);
    // Expression<Func<SysEmployee, bool>> where2 =
    // InitSearch<SysEmployee>(form);//查询转换成常量对象,里面已做了null判断了 var temp2 =
    // db.SysEmployee.Where(where2); var list2 = await temp2.ToListAsync(); Console.WriteLine(list2.Count);

    //    Stopwatch sw = new Stopwatch();
    //    for (var i = 0; i < 2; i++)
    //    {
    //        sw.Start();
    //        var result = bll.GetListByPage(1, 10);
    //        var first = sw.ElapsedMilliseconds;
    //        var result2 = await GetSysEmployeeListByPage(1, 10);
    //        var second = sw.ElapsedMilliseconds;
    //        sw.Stop();
    //        sw.Reset();
    //        Console.WriteLine($"first:{first};second:{second - first};result.Result.Count:{result.Result.Count}");
    //    }
    //}

    /// <summary>
    /// 分页方法
    /// </summary>
    /// <param name="index"></param>
    /// <param name="size"></param>
    /// <param name="form"></param>
    /// <param name="sortField"></param>
    /// <param name="asc"></param>
    /// <returns></returns>
    private static async Task<AjaxResult<dynamic>> GetSysEmployeeListByPage(int index, int size,
        IFormCollection form = null, string sortField = "", bool asc = false)
    {
        using (var db = Db)
        {
            var where = InitSearch<SysEmployee>(form, new SysEmployeeBll().InitSearchDelegete); //拼接查询条件方法

            #region 拼接查询条件

            if (form != null)
            {
            }

            #endregion 拼接查询条件

            int counts;
            var tempIDList = db.SysEmployee.ExOrderBy(sortField, asc).ExGetListByPage(index, size, out counts, where)
                .Select(m => m.SysEmployeeID);
            var result = new AjaxResult<dynamic> { Success = true };
            result.Total = counts;
            var list = db.SysEmployee.Where(m => tempIDList.Contains(m.SysEmployeeID)).ExOrderBy(sortField, asc)
                .AsNoTracking();
            result.Result = await list.Select(m => new
            {
                m.SysEmployeeID,
                m.EnumQuitStatus,
                m.SysEmployeeName,
                m.PY,
                SysEmployeePhone = DbFun.fn_replaceNum(m.SysEmployeePhone, CanSeePhone),
                m.UserCode,
                UpdateEmployeeID = m.UpdateSysEmployeeID,
                m.UpdateDate,
                m.CanSeePhone,
                m.IsDemo,
                m.IsDel,
                m.Remark,
                m.HeaderUrl,
                m.SysOperator,
                LastDate = db.SysLog.OrderByDescending(n => n.ID)
                    .FirstOrDefault(n => n.EnumLogType == EnumLogType.登录 && n.SysEmployeeID == m.SysEmployeeID)
                    .CreateDate
            }).ToListAsync();
            return result;
        }
    }

    #endregion EFCore Contains就是like查询的拼接,不需要使用EF.Functions.Like

    #region 测试加密空字符串

    public static void TestNullStringEncrypt()
    {
        var temp = DEncryptHelper.Encrypt("");
        Console.WriteLine("加密结果:" + temp);
        var temp2 = DEncryptHelper.Decrypt(temp);
        Console.WriteLine("解密结果:" + temp2);
        Console.ReadLine();
    }

    #endregion 测试加密空字符串

    #region 测试new DbEntites多个加事务的时候会不会占满数据库请求连接;数据库连接字符串内容  pooling=true;Max Pool Size=1000;Connection Lifetime=10

    public static void TestManyDb()
    {
        var commond = "100";
        while (commond.ExToInt32() > 0)
        {
            var len = commond.ExToInt32();
            using var dbCommon = DbNoFilter;
            Console.WriteLine("初始化第一个DbEntities成功");
            for (var i = 0; i < len; i++)
            {
                var temp1 = dbCommon.SysLog.FirstOrDefault(m => m.ID == 1);
                var tempI = i;
                Task.Run(() =>
                {
                    using var db = DbNoFilter;
                    using var tran = db.Database.BeginTransaction();
                    try
                    {
                        var tempID = tempI + 1;
                        var temp2 = db.SysLog.FirstOrDefault(m => m.ID == tempID);
                        var sysLog = new SysLog
                        {
                            BeforeVal = string.Empty,
                            CreateDate = DateTime.Now,
                            EnumLogType = EnumLogType.作废,
                            GetUrl = string.Empty,
                            ID = 0,
                            IPAddress = "127.0.0.1",
                            PostForm = string.Empty,
                            PostVal = string.Empty,
                            Remark = string.Empty,
                            SysCustomerID = null,
                            SysEmployeeID = null,
                            TblID = tempI,
                            TblName = "无",
                            UserAgent = string.Empty
                        };
                        db.SysLog.Add(sysLog);
                        db.SaveChanges();
                        Thread.Sleep(1);
                        tran.Commit();
                        Console.WriteLine($"进度:{tempI}/{len}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"({tempI})报错:{ex.ExString()}");
                        tran.Rollback();
                    }
                });
                //Thread.Sleep(1);
            }

            GC.Collect();
            Thread.Sleep(1000);
            Console.Write("输入循环次数(0次及其它退出):");
            commond = Console.ReadLine();
        }
    }

    #endregion 测试new DbEntites多个加事务的时候会不会占满数据库请求连接;数据库连接字符串内容  pooling=true;Max Pool Size=1000;Connection Lifetime=10

    #region 测试WxOpenSdkHelper.GetInfoBySonPrimary(EnumWxType.客户端, EnumOpenIDType.微信公众号,2);

    /// <summary>
    /// 测试WxOpenSdkHelper.GetInfoBySonPrimary(EnumWxType.客户端, EnumOpenIDType.微信公众号,2);
    /// </summary>
    public static void TestWxOpenSdkHelperGetInfoBySonPrimary()
    {
        var appInfoAr = WxOpenSdkHelper.GetInfoBySonPrimary(EnumWxType.客户端, EnumOpenIDType.微信公众号, "2");
        Console.WriteLine(appInfoAr.ExToJson());
        Console.Read();
    }

    #endregion 测试WxOpenSdkHelper.GetInfoBySonPrimary(EnumWxType.客户端, EnumOpenIDType.微信公众号,2);

    #region base64转文件

    /// <summary>
    /// base64转文件
    /// </summary>
    public static void ConvertToFile()
    {
        var fileName = @"F:\temp\新文件 2.txt";
        var jObject = JsonHelper.DeserializeObject(File.ReadAllText(fileName)) as JObject;
        if (jObject == null)
        {
            Console.WriteLine("不是json格式;");
            Console.Read();
            return;
        }

        var base64 = jObject["file"].ToString();
        var bytes = Convert.FromBase64String(base64);
        var toFileName = @"F:\temp\target.pdf";
        using var fs = new FileStream(toFileName, FileMode.OpenOrCreate);
        fs.Write(bytes, 0, bytes.Length);
        bytes = null;
        Console.Read();
    }

    #endregion base64转文件

    #region 测试like和等于的sql语句生成个

    /// <summary>
    /// 测试like和等于的sql语句生成个
    /// </summary>
    public static void TestEqualAndLike()
    {
        //using var db = Db;
        //var dic = new Dictionary<string, StringValues>
        //{
        //    { "ProjectName", "蓦然软件" }
        //};
        //IFormCollection form = new FormCollection(dic);
        //Expression<Func<Project, bool>> where = m => true;
        //where = EfSearchHelper.InitSearch(form, where);
        //var tempList = db.Project.Where(where);
        //var sql = tempList.ToQueryString();
        //var list = tempList.ToList();
        //Console.WriteLine(list.Count);
        //Console.WriteLine(sql);

        //var dic2 = new Dictionary<string, StringValues>
        //{
        //    { "$$ProjectName", "蓦然软件" }
        //};
        //IFormCollection form2 = new FormCollection(dic2);
        //Expression<Func<Project, bool>> where2 = m => true;
        //where2 = EfSearchHelper.InitSearch(form2, where2);
        //var tempList2 = db.Project.Where(where2);
        //var sql2 = tempList2.ToQueryString();
        //var list2 = tempList2.ToList();
        //Console.WriteLine(list2.Count);
        //Console.WriteLine(sql2);

        //var dic3 = new Dictionary<string, StringValues>
        //{
        //    { "ToBeDealMsg$ComputerMD5__ToBeDealMsg$Message", "abc" }
        //};
        //IFormCollection form3 = new FormCollection(dic3);
        //Expression<Func<Project, bool>> where3 = m => true;
        //where3 = EfSearchHelper.InitSearch(form3, where3);
        //var tempList3 = db.Project.Where(where3);
        //var sql3 = tempList3.ToQueryString();
        //var list3 = tempList3.ToList();
        //Console.WriteLine(list3.Count);
        //Console.WriteLine(sql3);

        //var dic4 = new Dictionary<string, StringValues>
        //{
        //    { "$$ToBeDealMsg$ComputerMD5__$$ToBeDealMsg$Message", "abc" }
        //};
        //IFormCollection form4 = new FormCollection(dic4);
        //Expression<Func<Project, bool>> where4 = m => true;
        //where4 = EfSearchHelper.InitSearch(form4, where4);
        //var tempList4 = db.Project.Where(where4);
        //var sql4 = tempList4.ToQueryString();
        //var list4 = tempList4.ToList();
        //Console.WriteLine(list4.Count);
        //Console.WriteLine(sql4);

        //Console.Read();
    }

    #endregion 测试like和等于的sql语句生成个

    #region 测试List查询

    /// <summary>
    /// 测试List查询
    /// 第一次比较满,要花费5秒+
    /// </summary>
    public static void TestGetList()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        var bll = new SysCustomerBll();
        Console.WriteLine($"声明Bll耗时:{sw.ElapsedMilliseconds}");
        var a = bll.GetListByPage(1, 10);
        Console.WriteLine($"GetAwaiter之前耗时:{sw.ElapsedMilliseconds}");
        var result = a.GetAwaiter().GetResult();
        Console.WriteLine($"GetAwaiter之后耗时:{sw.ElapsedMilliseconds}");
        Console.WriteLine(result.ExToJson());
        Console.WriteLine($"输出ToJson耗时:{sw.ElapsedMilliseconds}");
        sw.Stop();
        Console.WriteLine($"总耗时:{sw.ElapsedMilliseconds}");
        Console.WriteLine("输出任意字符回车继续(输入q退出):");
        var input = Console.ReadLine();
        if (input != "q")
        {
            TestGetList();
        }
    }

    #endregion

    #region 测试List查询Asyn

    /// <summary>
    /// 测试List查询Asyn
    /// 第一次比较满,要花费5秒+
    /// </summary>
    public static async Task TestGetListAsyn()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        var bll = new SysCustomerBll();
        Thread.Sleep(1000);
        Console.WriteLine($"声明Bll,await调用前耗时:{sw.ElapsedMilliseconds}");
        //var result = await bll.GetListByPage(1, 10);
        var result = await TestGetListAsynPart();
        Console.WriteLine($"await调用后:{sw.ElapsedMilliseconds}");
        Thread.Sleep(1000);
        Console.WriteLine($"这里是分割线,下面就会使用await调用了的值,此时耗时:{sw.ElapsedMilliseconds}");
        Console.WriteLine(result.ExToJson());
        Console.WriteLine($"输出ToJson耗时:{sw.ElapsedMilliseconds}");
        sw.Stop();
        Console.WriteLine($"总耗时:{sw.ElapsedMilliseconds}");
        Console.WriteLine("输出任意字符回车继续(输入q退出):");
        var input = Console.ReadLine();
        if (input != "q")
        {
            await TestGetListAsyn();
        }
    }

    private static async Task<List<string>> TestGetListAsynPart()
    {
        Thread.Sleep(2000);
        List<string> list = null;
        await Task.Run(() =>
        {
            list = new List<string>() { "aa", "bb" };
            Thread.Sleep(3000);
        });
        return list;
    }

    #endregion

    //#region 测试ExCopy方法的

    //public void TestExCopy()
    //{
    //    ShowProjectFromPage postModel = new ShowProjectFromPage()
    //    {
    //        ShowProjectID = 1,
    //        ProjectName = "项目1",
    //        MD5 = "",
    //        Remark = "备注",
    //        ShowProjectDetail = new List<ShowProjectDetailFromPage>()
    //        {
    //            new ShowProjectDetailFromPage()
    //            {
    //                Name = "名称1",
    //                Remark = "明细备注1",
    //                Url = "路径1",
    //            },
    //            new ShowProjectDetailFromPage()
    //            {
    //                Name = "名称2",
    //                Remark = "明细备注2",
    //                Url = "路径2",
    //            }
    //        },
    //        ShowQR = true,
    //        UrlDomain = "http://1"
    //    };
    //    ShowProject model = new ShowProject();
    //    model.ExCopyFrom(postModel);
    //    Console.WriteLine("TestExCopy");
    //    Console.WriteLine(model.ExToJson());
    //}

    //#endregion

    //#region 测试GetListByPage的Select结果

    //public void TestGetListByPage()
    //{
    //    var bll = new ShowProjectBll();
    //    //Dictionary<string, StringValues> dic = new Dictionary<string, StringValues>()
    //    //{
    //    //    {"ShowProjectDetail.Name", "测试%"}
    //    //};

    //    //IFormCollection form = new FormCollection(dic);
    //    IFormCollection form = new FormCollection(null);
    //    //form = form.ExAdd("ShowProjectDetail.Name", "测试%");
    //    form = form.ExAdd("CreateDate", "Sun Jul 04 2021 00:00:00 GMT+0800 (中国标准时间),Mon Jul 12 2021 00:00:00 GMT+0800 (中国标准时间)");
    //    var r = bll.GetListByPage(1, 10, form);
    //    Console.WriteLine(r.ExToJson());
    //    Console.ReadLine();
    //}

    //public void TestBinaryFormatter()
    //{
    //    //string base64 = "pgMAAMkAAAAfiwgAAAAAAAAKpVRbj9tUEJ44m8tewvUPWHkljmzv2o6zBMlxam0oaSO8XFQMlS9ns2Yd2xzbIgGhFRIPvIHEY+EBCXikSEitqlLxZza0/2KZE4dCqz4gNUcnnvN5Lt/MmfH7Q6sCm1/l8hI43FXcW7hruOt1qECjgS/XGk0Abi3g/0tD68rQGlqWKIqGqCoycIhWJKjiY0tWdBm2UHpZE/uq2leUvm72Zblv6VBD+MXpaZglMW8bxwZv2yOoI7inSLIkKvq+3BNFaCDygqTLXUntdTWtK2kaNBFr3bh6NDVlURUdlGAboe3HEOwwPwv1QPDcjAT81IRdRHYlVdcPkKSEKnvM8bUk5400jULf9SICrTV2pCxuaouRubg5Gi3OsRyItle3bq3u/vDou18efnXn0YPbF/fvrO7+fPHg+9WvPwnvEc9Iw3XKJHBzl8+Sgvpk0HWyTyJZlLTDMA7z0I14H99GyWxwnOBzSpOPiZ8fFhmhfBgMMvcwdbPs04SivDF0S3J5iFWK3TkZeCQOQlbTyuHn7UkSFBF5l9AM34+Ddr994mv7uuxLgiJJsnDQ812hp6qKoIu9E7enyF7g6+1O28gyMvei5XFi5zSMZ2i5plRm0uE3LgdSV8SlaR3eLKK8oGQQkyKnbtThp4WHzK4S9HFG4kFcRBE6tsKIWCheQ67o1Oo7zpWFmQTEcTbpOs6IzBPHeXj/j9W3X1/8+eNfX95e3ft99c1vjvMfDo7jhTHT9YqZ48QkV7riEwrdYB3wHSyeTXxK8qwsgOp7ElElQQyknnCwrwSCrhFFCDSiI7Sv9gyj/QVr63NcUGN9DHD+ETCalHTtxD8j+RGJUkJfm5Asc2dkHJ8kHb5UeLo24v8rTQOjVMFO4grOTgXe5vC0B1GY5VZIr9NRSKuwBdswXObEoNRd1pBaFSbZjAM2fXYdGrADZhSSOGd8Gghjv73OBpE5h/MPn5nCvxbPmUENgzTBTOZpkRPaxOC7sLlSdtksoVdg5JlJHCOE7svO4tZpXc9PCX0TR53DtOowThkhDv0x4h88m/gm0nPSbmGIGphpMR5xyBkzSAszKeKcEa6z0+ToBiO5AxPXN4KA4p2XLEdhdsas6mjFZDv8DNNsYDrj9LFiE1rwVjILY9aIZSG28Wb/YV8iO7jsZZaT+fEyxfMuvArlJ+B0meF4RxMcCbrk0LABw8SlAYvbYv3ADqURW/BG+ZW+vIfy37xmKFG3BQAA";
    //    //var buffer = Convert.FromBase64String(base64);
    //    //var bytes = buffer.Skip(8).ToList();
    //    //Stopwatch sw = new Stopwatch();
    //    //sw.Start();
    //    //var messageInfo = ExCore.SocketHelper.MessageInfo.DeserializeObject(bytes.ToArray());
    //    //sw.Stop();
    //    //Console.WriteLine(sw.ElapsedMilliseconds);
    //    //Console.WriteLine(messageInfo.ExToJson());
    //    //string json = "";
    //    //ExCore.SocketHelper.MessageInfo obj = JsonHelper.DeserializeObject<ExCore.SocketHelper.MessageInfo>(json);
    //    //var bytes = SerializeHelper.Serialize(obj);
    //    //Stopwatch sw = new Stopwatch();
    //    //sw.Start();
    //    //var obj2 = SerializeHelper.Deserialize<ExCore.SocketHelper.MessageInfo>(bytes);
    //    //sw.Stop();
    //    //Console.WriteLine(sw.ElapsedMilliseconds);
    //    //Console.WriteLine(obj2.ExToJson());
    //}

    //#endregion

    #region TestRoslyn

    public void TestRoslyn()
    {
        var fileFullName = @"F:\SysRolePostBll.cs";
        var csCode = File.ReadAllText(fileFullName);
        var tree = CSharpSyntaxTree.ParseText(csCode);
        var root = tree.GetCompilationUnitRoot();
        //Console.WriteLine($"The tree is a {root.Kind()} node.");
        //Console.WriteLine($"The tree has {root.Members.Count} elements in it.");
        //Console.WriteLine($"The tree has {root.Usings.Count} using statements. They are:");
        //foreach (UsingDirectiveSyntax element in root.Usings)
        //    Console.WriteLine($"\t{element.Name}");
        var firstMember = root.Members[0]; //命令空间
        //Console.WriteLine($"The first member is a {firstMember.Kind()}.");
        var nameSpaceDeclaration = (NamespaceDeclarationSyntax)firstMember; //命令空间
        var firstClass = (ClassDeclarationSyntax)nameSpaceDeclaration.Members[0];
        //MethodDeclaration
        //FieldDeclaration
        //PropertyDeclaration
        //ClassDeclaration
        const string methodName = "GetListSelect2";
        var has = false;
        var list = firstClass.Members;
        foreach (var item in list)
        {
            //string name = item.TryGetInferredMemberName();
            //string name = ((MethodDeclarationSyntax)item).Identifier.Text;
            var name = string.Empty;
            if (item is MethodDeclarationSyntax)
            {
                name = ((MethodDeclarationSyntax)item).Identifier.Text;
                if (name == methodName) has = true;
            }
            else if (item is PropertyDeclarationSyntax)
            {
                name = ((PropertyDeclarationSyntax)item).Identifier.Text;
            }
            else if (item is FieldDeclarationSyntax)
            {
                var field = (FieldDeclarationSyntax)item;
                name = field.Modifiers + " " + field.Declaration.Variables; //.Text;
            }
            else if (item is ClassDeclarationSyntax)
            {
                name = ((ClassDeclarationSyntax)item).Identifier.Text;
            }

            object kind = item.Kind();
            Console.WriteLine(name + "   item.Kind():" + kind);
        }

        #region 以下是改写代码

        //以下是改写代码
        var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
        var compilation = CSharpCompilation.Create("MyCompilation",
            new[] { tree }, new[] { mscorlib });
        // 获得语义模型
        var model = compilation.GetSemanticModel(tree);
        var oldRoot = model.SyntaxTree.GetRoot();
        // 用Visit重写代码
        var rw = new LiteralRewriter();
        rw.HasMethod = has;
        rw.MethodName = methodName;
        var newRoot = rw.Visit(oldRoot);
        // 新生成代码
        var strNewCode = newRoot.GetText().ToString();
        Console.WriteLine(strNewCode);

        #endregion 以下是改写代码

        Console.ReadLine();

        Console.Read();
    }

    private class LiteralRewriter : CSharpSyntaxRewriter // 继承CSharpSyntaxRewriter
    {
        public bool HasMethod;

        public string MethodName = "";

        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            if (HasMethod == false)
            {
                var newMethod =
                    SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName("\r\n\t\tpublic AjaxResult<dynamic> "),
                        MethodName);
                node = node.AddMembers(newMethod);
            }

            return base.VisitClassDeclaration(node);
        }

        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            return base.VisitMethodDeclaration(node);
        }

        /// <summary>
        /// 重载 VisitLiteralExpression 方法, 输入节点是 文字表达式
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            //if (node.IsKind(SyntaxKind.StringLiteralExpression))
            //{
            //    // 重新构造一个字符串表达式
            //    var retVal = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
            //        SyntaxFactory.Literal("重写,改变全部的字符串值"));
            //    return retVal;
            //}
            return base.VisitLiteralExpression(node);
        }
    }

    #endregion TestRoslyn

    #region 测试Or拼接条件的sql

    /// <summary>
    /// 测试Or拼接条件的sql
    /// </summary>
    public static void TestOrSearch()
    {
        using var db = Db;
        Expression<Func<SysEmployee, bool>> where = m =>
            true && m.SysEmployeeID == 1 && m.EnumQuitStatus == EnumQuitStatus.在职;
        where = where.ExOr(m => m.SysEmployeeName.Contains("Admin"));
        where = where.ExAnd(m => m.CanSeePhone);
        var temp = db.SysEmployee.Where(where);
        //OR拼接的sql查看一下(是否带了IsDel这个默认筛选条件)
        //SELECT[s].[SysEmployeeID], [s].[CanSeePhone], [s].[EnumQuitStatus], [s].[HeaderUrl], [s].[IsDel], [s].[IsDemo], [s].[PY], [s].[Remark], [s].[SysEmployeeName], [s].[SysEmployeePhone], [s].[SysOperatorID], [s].[UpdateDate], [s].[UpdateEmployeeID], [s].[UserCode]
        //FROM[SysEmployee] AS[s]
        //WHERE([s].[IsDel] = CAST(0 AS bit)) AND(((([s].[SysEmployeeID] = 1) AND([s].[EnumQuitStatus] = 0)) OR([s].[SysEmployeeName] LIKE N'%Admin%')) AND([s].[CanSeePhone] = CAST(1 AS bit)))
        //var list = temp.ToList();
        //Console.WriteLine(list.Count);
        var b = temp.Select(m => new SysEmployee
        {
            SysEmployeeID = m.SysEmployeeID,
            Remark = m.Remark
        }).FirstOrDefault();
        b.Remark = "222";
        db.SaveChanges();
        var a = temp.FirstOrDefault();
        //a.Remark = "111";
        //db.SaveChanges();
        Console.WriteLine(a.ExToJson());

        Console.WriteLine("TestAwaitDo之前");
        var task = TestAwaitDo();
        var awaiter = task.GetAwaiter();
        awaiter.GetResult();//这个会导致同步
        Console.WriteLine("TestAwaitDo之后");
        //task.Start();//System.InvalidOperationException
        //      HResult = 0x80131509
        //Message = Start may not be called on a promise - style task.
        //Source = System.Private.CoreLib
        //StackTrace:
        //      在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
        // 在 System.Threading.Tasks.Task.Start(TaskScheduler scheduler)
        // 在 System.Threading.Tasks.Task.Start()
        // 在 TrainingReminderSystem.Bll.TestBll.TestOrSearch() 在 F:\ExCode\Project\Demo\综合信息平台\TrainingReminderSystem.Bll\Test\TestBll.cs 中: 第 1163 行
        // 在 Test.Program.< Main > d__0.MoveNext() 在 F:\ExCode\Project\Demo\综合信息平台\Test\Program.cs 中: 第 33 行

        TestTaskDelay();

        Console.Read();
    }

    private static async Task TestAwaitDo()
    {
        using var db = Db;
        var a = await db.SysEmployee.Select(m => new SysEmployee
        {
            SysEmployeeID = m.SysEmployeeID,
            Remark = m.Remark
        }).FirstOrDefaultAsync();
        Console.WriteLine($"TestAwaitDo此方法执行了,{a.ExToJson()}");
    }

    /// <summary>
    /// 延迟取消问题
    /// </summary>
    public static void TestTaskDelay()
    {
        Console.WriteLine("TestTaskDelay之前");
        var cancelTokenSource = new CancellationTokenSource();
        const int cancelAfterTime = 3000;
        cancelTokenSource.CancelAfter(3000);
        var task2 = Task.Run(async () =>
        {
            Console.WriteLine("TestTaskDelay中的休息5秒后执行的第一步");
            await Task.Delay(5000, cancelTokenSource.Token);//Thread.Sleep(5000);
            Console.WriteLine("TestTaskDelay中的休息5秒后执行的最后一步");
        }, cancelTokenSource.Token);
        task2.CatchAsync((Exception ex) =>
        {
            Console.WriteLine($"task2异常:{ex.ExFullString()}");
        });
        Task.Run(async () =>
        {
            int count = 0;
            const int sleepTime = 10;
            int maxCount = cancelAfterTime / sleepTime;
            while (cancelTokenSource.IsCancellationRequested == false && count <= maxCount)
            {
                await Task.Delay(sleepTime); //Thread.Sleep(sleepTime);
                count++;
            }
            if (task2.IsCompleted)
            {
                return;
            }
            //task2.Dispose();//System.InvalidOperationException:“A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).”
        });
        Task.Factory.StartNew(() =>
        {

        });


        Console.WriteLine("TestTaskDelay之后");

        Console.ReadLine();
    }

    public static void TestOpenHBuilderX()
    {
        var fileFullName = @"F:\ExCode\Project\Demo\官网后台PC端\src\Auto\Project\ProjectAddEdit.vue";
        //System.Diagnostics.Process.Start("Explorer", $"/select,\"{fileFullName}\"");//打开此文件目录并选择此文件
        //System.Diagnostics.Process.Start("cmd", $"start \"{fileFullName}\"");
        var temp = ExeCmd($"\"{fileFullName}\"");
        Console.WriteLine(temp);
        //var temp = ExeCmd(@"cli open --file ");
        //Console.WriteLine(temp);
    }

    /// <summary>
    /// 执行cmd命令
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <returns></returns>
    private static string ExeCmd(string cmd)
    {
        var p = new Process
        {
            StartInfo =
            {
                FileName = "cmd.exe",
                UseShellExecute = false, //是否使用操作系统shell启动
                RedirectStandardInput = true, //接受来自调用程序的输入信息
                RedirectStandardOutput = true, //由调用程序获取输出信息
                RedirectStandardError = true, //重定向标准错误输出
                CreateNoWindow = true //不显示程序窗口
            }
        };
        p.Start(); //启动程序

        //向cmd窗口发送输入信息
        p.StandardInput.WriteLine(cmd);
        p.StandardInput.WriteLine("exit");
        p.StandardInput.AutoFlush = true;
        //p.StandardInput.WriteLine("exit");
        //向标准输入写入要执行的命令。这里使用&是批处理命令的符号，表示前面一个命令不管是否执行成功都执行后面(exit)命令，如果不执行exit命令，后面调用ReadToEnd()方法会假死
        //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令，后者表示必须前一个命令执行失败才会执行后面的命令

        //获取cmd窗口的输出信息
        var r = p.StandardOutput.ReadToEnd();
        p.Close();
        return r;
    }

    #endregion 测试Or拼接条件的sql
}
